<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="计划单编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入计划单编号" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startTime">
              <j-date placeholder="请选择开始日期" v-model="model.startTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endTime">
              <j-date placeholder="请选择结束日期" v-model="model.endTime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24" >-->
<!--            <a-form-model-item label="提报日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="submissionDate">-->
<!--              <j-date placeholder="请选择提报日期" v-model="model.submissionDate" style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24" >-->
<!--            <a-form-model-item label="是否开启" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">-->
<!--              <a-input v-model="model.status" placeholder="请输入是否开启" ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="原料采购计划单明细" :key="refKeys[0]" :forceRender="true">
              <div class="table-operator">
                <a-button @click="handleAddApplications" type="primary" icon="plus">新增</a-button>
              </div>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussMaterialProcurementPlanDetailTable.loading"
          :columns="bussMaterialProcurementPlanDetailTable.columns"
          :dataSource="bussMaterialProcurementPlanDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
          @cell-click="cellClickEvent"
          />
      </a-tab-pane>
    </a-tabs>
    <buss-application-list-modal ref="selectApplication"
                                 @applicationOk="applicationOk"
                                 :category="applicationId"
                                 checkval='checkbox'>

    </buss-application-list-modal>
    <goods-supplier-list-modal ref="selectSuppliersList"
                                   @supplierOk="supplierOk"
                                   :category="category">
    </goods-supplier-list-modal>


  </a-spin>
</template>

<script>

import { getAction, postAction, putAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import GoodsSupplierListModal from "@comp/base/modal/GoodsSupplierListModal";
  import BussApplicationListModal from '@comp/base/modal/BussApplicationListModal'

  export default {
    name: 'BussMaterialProcurementPlanForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      GoodsSupplierListModal,
      BussApplicationListModal
    },
    props: [{
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    }, "applications"],
    data() {
      return {
        categoryOptions: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        category: '1',
        applicationId: '1',
        row: {},
        model:{
          code: '',
          applicationId: '',
          submissionDate: '',
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          startTime: [
            { required: true, message: '请选择开始日期!' }
          ],
          endTime: [
            { required: true, message: '请选择结束日期!' }
          ]
        },
        refKeys: ['bussMaterialProcurementPlanDetail', ],
        tableKeys:['bussMaterialProcurementPlanDetail', ],
        activeKey: 'bussMaterialProcurementPlanDetail',
        // 原料采购计划单明细
        bussMaterialProcurementPlanDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '原料编号',
              key: 'materialCode',
               // type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '原料名称',
              key: 'materialName',
               // type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格',
              key: 'spec',
               // type: JVXETypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '供货单位',
              key: 'supplierName',
              width: '180px',
              // 使用内置的下拉选项组件
              // widget: 'select',
              // // 下拉选项的数据
              // options: []
            },
            {
              title: '现有库存',
              key: 'number',
              // type: JVXETypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '安全库存',
              key: 'stockQuantity',
              // type: JVXETypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '计划采购',
              key: 'num',
               type: JVXETypes.input,
              width:"120px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '到货日期',
              key: 'arrivalDate',
               // type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            // {
            //   title: '物料id',
            //   key: 'materialId',
            //   type: JVXETypes.hidden,
            //   width:"200px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            // },
          ]
        },
        url: {
          add: "/plan/bussMaterialProcurementPlan/add",
          edit: "/plan/bussMaterialProcurementPlan/edit",
          queryById: "/plan/bussMaterialProcurementPlan/queryById",
          bussMaterialProcurementPlanDetail: {
            list: '/plan/bussMaterialProcurementPlan/queryBussMaterialProcurementPlanDetailByMainId',
            applicationDetail: '/plan/bussMaterialProcurementPlan/applicationDetail',
            applicationDetailById: '/plan/bussMaterialProcurementPlan/applicationDetailById',
          },
        }
      }
    },

    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    // watch: {
    //   // 监听需要动态获取下拉列表的ID字段
    //   'dataSource.materialId': {
    //     immediate: true,
    //     handler(newId) {
    //       if (newId) {
    //         // 根据ID获取下拉列表
    //         this.fetchDropdownOptions(newId);
    //       }
    //     }
    //   }
    // },
    methods: {
      getSequenceNum() {
        let url = "/sys/fillRule/executeRuleByCode/cgjhd";
        putAction(url, {}).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model.code = res.result;
          }
        })
      },
      handleAddApplications(){
        this.$refs.selectApplication.add();
        this.$refs.selectApplication.title = "选择请购明细";
        this.$refs.selectApplication.disableSubmit = false;
      },
      cellClickEvent({ row, column }) {
        if (column.property === 'supplierName') {
          this.row = row;
          this.category = row.materialId;
          console.log(this.category)
          this.$refs.selectSuppliersList.add();
          this.$refs.selectSuppliersList.title = "选择供应商";
          this.$refs.selectSuppliersList.disableSubmit = false;
        }
        // console.log(row)
        // console.log(column)
        // // 假设我们在 name 列点击时弹出弹框
        // if (column.property === 'supplierName') {
        //   this.$set(row, 'supplierName', '默认值');
        // }
      },
      supplierOk(res) {
        console.log(res)
        this.$set(this.row, 'supplierName', res.name);
        this.$set(this.row, 'supplierId', res.supplierId);
      },
      applicationOk(ids) {
        console.log("1")
        console.log(ids)
        let _this = this;
        postAction('/plan/bussMaterialProcurementPlan/applicationDetailById', { ids: ids }).then(res => {
          console.log("2")
          console.log(res.result)
          let erpGoodsList = res.result;
          erpGoodsList.forEach(function(item,index){
            console.log(item,index)
            let detail = {};
            detail.materialCode = item.materialCode;
            detail.materialName = item.materialName;
            detail.spec = item.spec;
            detail.number = item.number;
            detail.supplierName = item.supplierName;
            detail.supplierId = item.supplierId;
            detail.materialId = item.materialId;
            detail.stockQuantity = item.stockQuantity;
            detail.num = item.num;
            detail.remark = item.remark;
            detail.arrivalDate = item.arrivalDate;
            detail.applicationDetailId = item.applicationDetailId;
            // _this.$refs.refKeys[0].pushRows(detail);
            // console.log(_this.bussMaterialProcurementPlanDetailTable.dataSource);
            _this.bussMaterialProcurementPlanDetailTable.dataSource.push(detail);
          })
        })
        // let params = { id: res }
        // this.requestSubTableData(this.url.bussMaterialProcurementPlanDetail.applicationDetailById, params, this.bussMaterialProcurementPlanDetailTable)
      },
      addBefore(){
        this.bussMaterialProcurementPlanDetailTable.dataSource=[]

      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/cgjhd', {}).then(res => {
          this.model.code = res.result;
        })
      },
      add() {
        // this.edit(this.modelDefault);
        // this.getPfCode();
        console.log(this.applications);
        this.applicationId = this.applications.applicationId;
        this.model.applicationId = this.applications.applicationId;
        this.model.submissionDate = this.applications.createTime.length>10?this.applications.createTime.substr(0,10):this.applications.createTime;
        //todo 暂时没有供货商关联
        // let params = { id: this.applications.applicationId }
        // this.requestSubTableData(this.url.bussMaterialProcurementPlanDetail.applicationDetail, params, this.bussMaterialProcurementPlanDetailTable)
        console.log('点击新增了')
        this.getSequenceNum()
      },
      edit(record) {
        this.model = Object.assign({}, record);
        this.applicationId = this.model.applicationId;
        console.log(this.applications);
        this.visible = true;
        this.editAfter();
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          //todo 暂时没有供货商关联
          this.requestSubTableData(this.url.bussMaterialProcurementPlanDetail.list, params, this.bussMaterialProcurementPlanDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussMaterialProcurementPlanDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>